
import 'package:asperm/tools/user_repository.dart';
import 'package:asperm/tools/widget_extension.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import '../generated/l10n.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../tools/auth.dart';
import '../tools/const.dart';
import '../tools/divider_input_formatter.dart';
import '../tools/tools.dart';
import '../views/common_button.dart';
import '../views/myDialog.dart';

enum ProcessStep {
  inputNickname,  // 输入昵称
  inputAnswer,    // 输入答案
  showResult      // 得到结果
}
class SignUpPage extends StatefulWidget {
  SignUpPage({Key? key}) : super(key: key);

  @override
  State<SignUpPage> createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {


  final firstController = TextEditingController();
  final secondController = TextEditingController.fromValue(
      TextEditingValue());
  final thirdController = TextEditingController.fromValue(
      TextEditingValue());

  final fourthController = TextEditingController.fromValue(
      TextEditingValue());
  final fifthController = TextEditingController.fromValue(
      TextEditingValue());

  String firstValue = '';
  String secondValue = '';
  String thirdValue = '';
  String fourthValue = '';
  String fifthValue = '';

  bool isButtonEnabled = false;
  bool isAgreementSelected = false;
  bool isEmailLogin = false;



  final FocusNode focusNode_nickName = FocusNode();
  final FocusNode focusNode_password = FocusNode();

  int inputLength = 0;
  bool isVisitor = false;
  ProcessStep currentStep = ProcessStep.inputNickname;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  void dispose() {
    super.dispose();
    //释放
    focusNode_nickName.dispose();
    focusNode_password.dispose();

  }


  @override
  Widget build(BuildContext context) {
    // 获取屏幕大小
    final Size screenSize = MediaQuery.of(context).size;
    return Scaffold(
      body: GestureDetector(
          onTap: () {
            // 调用这个方法会隐藏软键盘
            FocusScope.of(context).unfocus();
          },
          child: ConstrainedBox(
            constraints: BoxConstraints(
              minHeight: screenSize.height, // 设置最小高度为屏幕高度
            ),
            child: Container(
              // 把Container放在SingleChildScrollView外面
              height: screenHeight(context),
              color: Colors.white,
              child:  SingleChildScrollView(
                child: Column(
                  // verticalDirection: VerticalDirection.down,
                  // mainAxisSize: MainAxisSize.max, // 添加这个属性
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        buildSmallLogo(context),
                        firstWidget(context),
                        secondWidget(context),
                        thirdWidget(context),
                        fourthWidget(context),
                        fifthWidget(context),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(bottom: 40.h),
                      child: Column(
                        children: [
                          buildLoginBtn(context),
                          buildLoginGuestBtn(context),

                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          )),
    );
  }



  //small logo
  Widget buildSmallLogo(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 78.h, left: 20.w),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            'Sign Up',
            style: TextStyle(
              color: Color(0xff5A5A5A),
              fontSize: 30.sp,
              fontWeight: FontWeight.w700,
            ),
            textAlign: TextAlign.center,
            maxLines: 1, // 限制文本显示的最大行数为2
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }
  Widget firstWidget(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Container(
            // color: Colors.red,
            margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                'Username',
                style: TextStyle(
                  color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
                  fontSize: 16.sp,
                  fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              left: 20.w,
              right: 20.w,
            ),
            height: 48.h,
            decoration: BoxDecoration(
              border: Border.all(
                color: Color(0xffDADADA), // 下划线颜色
                width: 1.h, //
              ),
              borderRadius: BorderRadius.circular(4.h),
            ),
            child: Row(
              children: [
                // Email输入TextField
                SizedBox(
                  width: 20.w,
                ),
                Expanded(
                  child: TextField(
                    focusNode: focusNode_nickName,
                    // autofocus: isEmailLogin,
                    controller: firstController,
                    maxLines: 1,
                    inputFormatters: [
                      // 限制输入长度为 20
                      LengthLimitingTextInputFormatter(20),
                      // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                      FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
                    ],
                    onChanged: (value) {
                      setState(() {
                        firstValue = value;

                        updateButtonEnabled();
                      });
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(borderSide: BorderSide.none),
                      // enabledBorder: UnderlineInputBorder(
                      //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 下划线颜色
                      // ),
                      // focusedBorder: UnderlineInputBorder(
                      //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 获得焦点时下划线颜色
                      // ),
                      // labelText: S.of(context).Email,
                      hintText: 'Enter Username',
                      hintStyle: TextStyle(
                        fontSize: 16.sp,
                        color: Color(0xff888888),
                        fontWeight: FontWeight.w400,
                      ),
                      contentPadding: EdgeInsets.symmetric(
                          vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
                    ),
                    keyboardType: TextInputType.text,
                    cursorColor: Color(0xFFffED6D20),
                    style: TextStyle(
                      fontSize: 16.sp,
                    ),
                  ),
                ),
                // 取消按钮，仅当有输入时显示
                Offstage(
                  offstage: firstValue.isEmpty,
                  child: IconButton(
                    alignment: Alignment.centerRight,
                    icon: Icon(
                      Icons.cancel,
                      color: Colors.grey,
                      size: 20.w,
                    ),
                    onPressed: () {
                      setState(() {
                        firstValue = '';
                        firstController.clear();
                        updateButtonEnabled();
                      });
                    },
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget secondWidget(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Container(
            // color: Colors.red,
            margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                'Password',
                style: TextStyle(
                  color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
                  fontSize: 16.sp,
                  fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              left: 20.w,
              right: 20.w,
            ),
            height: 48.h,
            decoration: BoxDecoration(
              border: Border.all(
                color: Color(0xffDADADA), // 下划线颜色
                width: 1.h, //
              ),
              borderRadius: BorderRadius.circular(4.h),
            ),
            child: Row(
              children: [
                // Email输入TextField
                SizedBox(
                  width: 20.w,
                ),
                Expanded(
                  child: TextField(
                    focusNode: focusNode_password,
                    // autofocus: isEmailLogin,
                    controller: secondController,
                    maxLines: 1,
                    inputFormatters: [
                      // 限制输入长度为 20
                      LengthLimitingTextInputFormatter(20),
                      // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                      FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
                    ],
                    onChanged: (value) {
                      setState(() {
                        secondValue = value;
                        updateButtonEnabled();
                      });
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(borderSide: BorderSide.none),
                      hintText: 'Enter Password',
                      hintStyle: TextStyle(
                        fontSize: 16.sp,
                        color: Color(0xff888888),
                        fontWeight: FontWeight.w400,
                      ),
                      contentPadding: EdgeInsets.symmetric(
                          vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
                    ),
                    keyboardType: TextInputType.text,
                    cursorColor: Color(0xFFffED6D20),
                    style: TextStyle(
                      fontSize: 16.sp,
                    ),
                  ),
                ),
                // 取消按钮，仅当有输入时显示
                Offstage(
                  offstage: secondValue.isEmpty,
                  child: IconButton(
                    alignment: Alignment.centerRight,
                    icon: Icon(
                      Icons.cancel,
                      color: Colors.grey,
                      size: 20.w,
                    ),
                    onPressed: () {
                      setState(() {
                        secondValue = '';
                        secondController.clear();
                        updateButtonEnabled();
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget thirdWidget(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Container(
            // color: Colors.red,
            margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                'Confirm Password',
                style: TextStyle(
                  color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
                  fontSize: 16.sp,
                  fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              left: 20.w,
              right: 20.w,
            ),
            height: 48.h,
            decoration: BoxDecoration(
              border: Border.all(
                color: Color(0xffDADADA), // 下划线颜色
                width: 1.h, //
              ),
              borderRadius: BorderRadius.circular(4.h),
            ),
            child: Row(
              children: [
                // Email输入TextField
                SizedBox(
                  width: 20.w,
                ),
                Expanded(
                  child: TextField(
                    // autofocus: isEmailLogin,
                    controller: thirdController,
                    maxLines: 1,
                    inputFormatters: [
                      // 限制输入长度为 20
                      LengthLimitingTextInputFormatter(20),
                      // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                      FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
                    ],
                    onChanged: (value) {
                      setState(() {
                        thirdValue = value;
                        updateButtonEnabled();
                      });
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(borderSide: BorderSide.none),
                      hintText: 'Confirm Password',
                      hintStyle: TextStyle(
                        fontSize: 16.sp,
                        color: Color(0xff888888),
                        fontWeight: FontWeight.w400,
                      ),
                      contentPadding: EdgeInsets.symmetric(
                          vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
                    ),
                    keyboardType: TextInputType.text,
                    cursorColor: Color(0xFFffED6D20),
                    style: TextStyle(
                      fontSize: 16.sp,
                    ),
                  ),
                ),
                // 取消按钮，仅当有输入时显示
                Offstage(
                  offstage: thirdValue.isEmpty,
                  child: IconButton(
                    alignment: Alignment.centerRight,
                    icon: Icon(
                      Icons.cancel,
                      color: Colors.grey,
                      size: 20.w,
                    ),
                    onPressed: () {
                      setState(() {
                        thirdValue = '';
                        thirdController.clear();
                        updateButtonEnabled();
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget fourthWidget(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Container(
            // color: Colors.red,
            margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                'Security Question',
                style: TextStyle(
                  color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
                  fontSize: 16.sp,
                  fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              left: 20.w,
              right: 20.w,
            ),
            height: 48.h,
            decoration: BoxDecoration(
              border: Border.all(
                color: Color(0xffDADADA), // 下划线颜色
                width: 1.h, //
              ),
              borderRadius: BorderRadius.circular(4.h),
            ),
            child: Row(
              children: [
                // Email输入TextField
                SizedBox(
                  width: 20.w,
                ),
                Expanded(
                  child: TextField(
                    // autofocus: isEmailLogin,
                    controller: fourthController,
                    maxLines: 1,
                    inputFormatters: [
                      // 限制输入长度为 20
                      LengthLimitingTextInputFormatter(20),
                      // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                      FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
                    ],
                    onChanged: (value) {
                      setState(() {
                        fourthValue = value;
                        updateButtonEnabled();
                      });
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(borderSide: BorderSide.none),
                      hintText: 'Enter Question',
                      hintStyle: TextStyle(
                        fontSize: 16.sp,
                        color: Color(0xff888888),
                        fontWeight: FontWeight.w400,
                      ),
                      contentPadding: EdgeInsets.symmetric(
                          vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
                    ),
                    keyboardType: TextInputType.text,
                    cursorColor: Color(0xFFffED6D20),
                    style: TextStyle(
                      fontSize: 16.sp,
                    ),
                  ),
                ),
                // 取消按钮，仅当有输入时显示
                Offstage(
                  offstage: fourthValue.isEmpty,
                  child: IconButton(
                    alignment: Alignment.centerRight,
                    icon: Icon(
                      Icons.cancel,
                      color: Colors.grey,
                      size: 20.w,
                    ),
                    onPressed: () {
                      setState(() {
                        fourthValue = '';
                        fourthController.clear();
                        updateButtonEnabled();
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget fifthWidget(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Container(
            // color: Colors.red,
            margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                'Security Answer',
                style: TextStyle(
                  color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
                  fontSize: 16.sp,
                  fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              left: 20.w,
              right: 20.w,
            ),
            height: 48.h,
            decoration: BoxDecoration(
              border: Border.all(
                color: Color(0xffDADADA), // 下划线颜色
                width: 1.h, //
              ),
              borderRadius: BorderRadius.circular(4.h),
            ),
            child: Row(
              children: [
                // Email输入TextField
                SizedBox(
                  width: 20.w,
                ),
                Expanded(
                  child: TextField(
                    // autofocus: isEmailLogin,
                    controller: fifthController,
                    maxLines: 1,
                    inputFormatters: [
                      // 限制输入长度为 20
                      LengthLimitingTextInputFormatter(20),
                      // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                      FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
                    ],
                    onChanged: (value) {
                      setState(() {
                        fifthValue = value;
                        updateButtonEnabled();
                      });
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(borderSide: BorderSide.none),
                      hintText: 'Enter Answer',
                      hintStyle: TextStyle(
                        fontSize: 16.sp,
                        color: Color(0xff888888),
                        fontWeight: FontWeight.w400,
                      ),
                      contentPadding: EdgeInsets.symmetric(
                          vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
                    ),
                    keyboardType: TextInputType.text,
                    cursorColor: Color(0xFFffED6D20),
                    style: TextStyle(
                      fontSize: 16.sp,
                    ),
                  ),
                ),
                // 取消按钮，仅当有输入时显示
                Offstage(
                  offstage: fifthValue.isEmpty,
                  child: IconButton(
                    alignment: Alignment.centerRight,
                    icon: Icon(
                      Icons.cancel,
                      color: Colors.grey,
                      size: 20.w,
                    ),
                    onPressed: () {
                      setState(() {
                        fifthValue = '';
                        fifthController.clear();
                        updateButtonEnabled();
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  updateButtonEnabled(){

    if(firstValue.length >0 && secondValue.length >0 && thirdValue.length >0 && fourthValue.length >0 && fifthValue.length >0){
      isButtonEnabled = true;
    }else{
      isButtonEnabled = false;
    }
  }

  //登录 事件
  loginAction() async {
    // 关闭键盘
    FocusScope.of(context).unfocus();
  }


  // 登录按钮
  Widget buildLoginBtn(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h),
      // 左右各16像素的边距
      child: AspectRatio(
        aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
        child: CommonButton(
          // title: S.of(context).Verification,
          isEnable: isButtonEnabled,
          title: 'Sign Up',
          borderRadius: 5.w,
          onTap: () async {

            loginAction();
            if(secondValue != thirdValue){
              showToast('Passwords do not match');
              return;
            }
            bool registerUser = await UserRepository().registerUser(username: firstValue, password: secondValue, securityQuestion: fourthValue, securityAnswer: fifthValue);
            if(!registerUser){
              showToast('Username already exists');
            }else{
              loginAction();
              showToast('登录成功');
              saveUsername(firstValue);
              Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false);
            }

          },
        ),
      ),
    );
  }

  Widget buildLoginGuestBtn(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h),
      // 左右各16像素的边距
      child: AspectRatio(
        aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
        child: CommonButton(
          // title: S.of(context).Verification,
          bgColor: Colors.transparent,
          title: 'Back',
          textColor: globalColor(),
          borderRadius: 5.w,
          onTap: () {

            loginAction();
            Navigator.pop(context);

          },
        ),
      ),
    );
  }

}
